# views.py
import json
from django.db.models import F
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import get_object_or_404, render
from django.urls import reverse
from django.views import generic
from django.core.paginator import Paginator

from .models import Choice, Question

class IndexView(generic.ListView):
    template_name = "polls/index.html"
    context_object_name = "latest_question_list"
    paginate_by = 5

    def get_queryset(self):
        return Question.objects.order_by("-pub_date")
    
    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        
        context['normal_questions'] = Question.objects.filter(
            question_type='normal'
        ).order_by('-pub_date')[:3]
        
        context['hot_questions'] = Question.objects.filter(
            question_type='hot'
        ).order_by('-pub_date')[:3]
        
        context['latest_questions'] = Question.objects.filter(
            question_type='latest'
        ).order_by('-pub_date')[:3]
        
        return context

class DetailView(generic.DetailView):
    model = Question
    template_name = "polls/detail.html"
    context_object_name = 'question'

def vote(request, question_id):
    question = get_object_or_404(Question, pk=question_id)
    try:
        selected_choice = question.choices.get(pk=request.POST["choice"])
    except (KeyError, Choice.DoesNotExist):
        return render(
            request,
            "polls/detail.html",
            {
                "question": question,
                "error_message": "您没有选择选项。",
            },
        )
    else:
        selected_choice.votes = F("votes") + 1
        selected_choice.save()
        return HttpResponseRedirect(reverse("polls:results", args=(question.id,)))

def results(request, question_id):
    question = get_object_or_404(Question, pk=question_id)
    
    # 准备图表数据 - 使用安全的 JSON 格式
    labels = [choice.choice_text for choice in question.choices.all()]
    data = [choice.votes for choice in question.choices.all()]
    
    # 找出得票最高的选项ID
    winner_id = -1
    if question.choices.exists():
        # 找到最高票数
        max_votes = max(choice.votes for choice in question.choices.all())
        # 找到第一个得票最高的选项
        winner = next((c for c in question.choices.all() if c.votes == max_votes), None)
        if winner:
            winner_id = winner.id
    
    # 确保数据是安全的 JSON 字符串
    context = {
        'question': question,
        'chart_labels': json.dumps(labels),
        'chart_data': json.dumps(data),
        'winner_id': winner_id,  # 添加获胜者ID
    }
    return render(request, 'polls/results.html', context)